package com.ruoyi.web.controller.net;

import com.ruoyi.net.domain.ElementDhcp;
import com.ruoyi.net.domain.NetElement;
import com.ruoyi.net.netconf.util.DeviceManager;
import com.ruoyi.net.service.INetElementService;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.net.domain.ElementIsis;
import com.ruoyi.net.service.IElementIsisService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 网元-ISIS配置Controller
 * 
 * @author net
 * @date 2024-11-17
 */
@Api(tags = "网元-ISIS配置")
@RestController
@RequestMapping("/element/isis")
public class ElementIsisController extends BaseController {
    @Autowired
    private IElementIsisService elementIsisService;

    @Autowired
    private INetElementService netElementService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private DeviceManager deviceManager;

    /**
     * 查询网元-ISIS配置列表
     */
    @ApiOperation(value = "查询网元-ISIS配置列表", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:isis:list')")
    @GetMapping("/list")
    public TableDataInfo list(ElementIsis elementIsis) {
        startPage();
        List<ElementIsis> list = elementIsisService.selectElementIsisList(elementIsis);
        return getDataTable(list);
    }

    /**
     * 导出网元-ISIS配置列表
     */
    @ApiOperation(value = "导出网元-ISIS配置列表", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:isis:export')")
    @Log(title = "网元-ISIS配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ElementIsis elementIsis) {
        List<ElementIsis> list = elementIsisService.selectElementIsisList(elementIsis);
        ExcelUtil<ElementIsis> util = new ExcelUtil<ElementIsis>(ElementIsis.class);
        util.exportExcel(response, list, "网元-ISIS配置数据");
    }

    /**
     * 获取网元-ISIS配置详细信息
     */
    @ApiOperation(value = "获取网元-ISIS配置详细信息", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:isis:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(elementIsisService.selectElementIsisById(id));
    }

    /**
     * 新增网元-ISIS配置
     */
    @ApiOperation(value = "新增网元-ISIS配置", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:isis:add')")
    @Log(title = "网元-ISIS配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ElementIsis elementIsis) {
        return toAjax(elementIsisService.insertElementIsis(elementIsis));
    }

    /**
     * 修改网元-ISIS配置
     */
    @ApiOperation(value = "修改网元-ISIS配置", httpMethod = "PUT")
    //    @PreAuthorize("@ss.hasPermi('system:isis:edit')")
    @Log(title = "网元-ISIS配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ElementIsis elementIsis) {
        return toAjax(elementIsisService.updateElementIsis(elementIsis));
    }

    /**
     * 删除网元-ISIS配置
     */
    @ApiOperation(value = "删除网元-ISIS配置", httpMethod = "DELETE")
    //    @PreAuthorize("@ss.hasPermi('system:isis:remove')")
    @Log(title = "网元-ISIS配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(elementIsisService.deleteElementIsisByIds(ids));
    }

    /**
     * 激活设备
     * @param id
     */
    @ApiOperation(value = "激活设备", httpMethod = "GET")
    @Log(title = "激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/activate/{id}")
    public AjaxResult activateDevice(@PathVariable("id") String id) {
        ElementIsis entity = elementIsisService.selectElementIsisById(id);
        entity.setStatus("1");
        if (sendXml(entity)){
            return toAjax(elementIsisService.updateElementIsis(entity));
        }else {
            return AjaxResult.error("激活设备失败");
        }
    }

    /**
     * 去激活设备
     * @param id
     */
    @ApiOperation(value = "去激活设备", httpMethod = "GET")
    @Log(title = "去激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/unactivate/{id}")
    public AjaxResult unactivateDevice(@PathVariable("id") String id) {
        ElementIsis entity = elementIsisService.selectElementIsisById(id);
        entity.setStatus("0");
        if (sendXml(entity)){
            return toAjax(elementIsisService.updateElementIsis(entity));
        }else {
            return AjaxResult.error("去激活设备失败");
        }
    }

    private boolean sendXml(ElementIsis entity) {
        boolean isSend = true;
        // TODO: 2024/11/28  设备联调，添加并激活
        if (sysConfigService.selectDebugEnabled()) {
            NetElement netElement = netElementService.getCacheObject(entity.getElementId());
            deviceManager.getDevice(netElement.getIp());

            String xml = "<isis xmlns=\"http://fiberhome.com/fhnw/yang/ipprotocol/routing/fos-isis\">" +
                    "    <isis-instances>" +
                    "      <isis-instance>" +
                    "        <instance-name>" + entity.getIsis() + "</instance-name>" +
                    // -------start 网络实体 ---------
                    /*"        <net>" +
                    "          <net-name>69.0001.1101.2601.0013.00</net-name>" +
                    "        </net>" +*/
                    // -------end  网络实体 ---------
                    "        <is-type>" + entity.getRouteLevel() + "</is-type>" +
                    "        <lsp-mtu>" + entity.getLspMaxLen() + "</lsp-mtu>" +
                    "        <ecmp-num>" + entity.getEqualRouteNum() + "</ecmp-num>" +
                    "        <lsp-lifetime>" + entity.getLspDuration() + "</lsp-lifetime>" +
                    // -------start 度量配置 ---------
                    /*"        <metric-style>" +
                    "          <level>level2</level>" +
                    "          <style>wide-metric-style</style>" +
                    "        </metric-style>" +*/
                    // -------end  度量配置 ---------
                    "        <sr-mpls>" +
                    "          <sr-mpls-enable>" + entity.getSrMplsEnable() + "</sr-mpls-enable>" +
                    "        </sr-mpls>" +
                    // ------start 防微环参数 -------
                    "        <micro-loop-avoidance>" +
                    "          <avoidance-flag>" + entity.getRemoteRingEnable() + "</avoidance-flag>" +
                    "        </micro-loop-avoidance>" +
                    // -------end 防微环参数 ----------
                    "        <overload-bit>" +
                    "          <interval>" + entity.getOverloadConfig() + "</interval>" +
                    "        </overload-bit>" +
                    "        <bgp-ls>" +
//                    "          <level>" + entity.getBgpLs().split("|")[0] + "</level>" +
//                    "          <bgp_ls_enable>" + entity.getBgpLs().split("|")[1] + "</bgp_ls_enable>" +
                    "        </bgp-ls>" +
                    "        <cspf-and-te>" +
//                    "          <cspf>"+entity.getTeConfig().split("|")[0]+"</cspf>" +
//                    "          <te-to-level>"+entity.getTeConfig().split("|")[1]+"</te-to-level>" +
                    "        </cspf-and-te>" +
                    // ------- start LSP刷新配置 --------
                    /*"        <lsp-refresh-interval>" +
                    "          <interval>900</interval>" +
                    "        </lsp-refresh-interval>" +*/
                    // ------- end LSP刷新配置 --------
                    // -------start IPV4地址族 ---------
                    /*"        <af>" +
                    "          <af-name>ipv4</af-name>" +
                    "          <saf-name>unicast</saf-name>" +
                    "          <af-data>" +
                    "            <mpls-te-router-id>" +
                    "              <router-id>110.126.10.13</router-id>" +
                    "            </mpls-te-router-id>" +
                    "          </af-data>" +
                    "        </af>" +*/
                    // -------end IPV4地址族 ---------
                    "        <passive-all-interface>" +
                    "          <enable>"+entity.getPassiveStatus()+"</enable>" +
                    "        </passive-all-interface>" +
                    "        <metric-delay-suppress>" +
//                    "          <time-value>" + entity.getDelayHoldPublish().split("|")[0] + "</time-value>" +
//                    "          <percent-value>" + entity.getDelayHoldPublish().split("|")[1] + "</percent-value>" +
//                    "          <absolute-value>" + entity.getDelayHoldPublish().split("|")[2] + "</absolute-value>" +
                    "        </metric-delay-suppress>" +
                    "      </isis-instance>" +
                    "    </isis-instances>" +
                    "  </isis>";
            System.out.println(xml);
            isSend = deviceManager.editConfig(xml, "merge");
        }
        return isSend;
    }
}